<template>
  <div style="position: relative">
    <div class="mask" v-if="handleType == 'look'"></div>
    <a-form
      ref="formRef"
      layout="vertical"
      :model="formState"
      :rules="rules"
      :wrapper-col="wrapperCol"
      style="display: flex; flex-wrap: wrap"
    >
      <a-form-item
        style="width: 50%; padding-right: 15px"
        ref="title"
        label="公告标题"
        name="title"
      >
        <a-input
          placeholder="请输入公告标题"
          v-model:value="formState.title"
        ></a-input>
      </a-form-item>
      <a-form-item
        style="width: 50%; padding-right: 15px"
        ref="type"
        label="发布类型"
        name="type"
        v-if="handleType == 'add'"
      >
        <a-select
          allowClear
          style="width: 100%"
          v-model:value="formState.type"
          placeholder="请选择发布类型"
        >
          <a-select-option
            v-for="item in typeList"
            :key="item.value"
            :value="item.value"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item
        v-if="formState.type == 'depart'"
        style="width: 50%; padding-right: 15px"
        ref="hospitalDepartId"
        label="所属科室"
        name="hospitalDepartId"
      >
        <a-tree-select
          v-model:value="formState.hospitalDepartId"
          style="width: 100%"
          :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
          :tree-data="departmentList"
          placeholder="请选择科室"
          tree-default-expand-all
        >
        </a-tree-select>
      </a-form-item>
      <a-form-item
        style="width: 50%; padding-right: 15px"
        ref="receiverRoleId"
        label="角色"
        name="receiverRoleId"
        v-if="formState.type == 'role'"
      >
        <a-select
          allowClear
          style="width: 100%"
          v-model:value="formState.receiverRoleId"
          placeholder="请选择角色"
        >
          <a-select-option
            v-for="item in roleLists"
            :key="item.id"
            :disabled="item.disabled"
            :value="item.id"
            >{{ item.name }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item
        v-if="formState.type == 'staff'"
        style="width: 50%; padding-right: 15px"
        ref="receiverIds"
        label="接收人"
        name="receiverIds"
      >
        <a-select
          mode="multiple"
          allowClear
          style="width: 100%"
          v-model:value="formState.receiverIds"
          placeholder="请选择接收人"
        >
          <a-select-option
            v-for="item in userList"
            :key="item.sysUserId"
            :value="item.sysUserId"
            >{{ item.realName }}</a-select-option
          >
        </a-select>
      </a-form-item>
      <a-form-item style="width: 100%" ref="picUrl" label="图片" name="picUrl">
        <a-upload
          v-model:file-list="fileList"
          accept="image/jpeg,image/png,.bmp"
          list-type="picture-card"
          multiple
          @preview="handlePreview"
          :before-upload="beforeUpload"
        >
          <plus-outlined />
          <div style="margin-top: 8px">上传</div>
        </a-upload>
        <a-modal
          :visible="previewVisible"
          :title="previewTitle"
          :footer="null"
          @cancel="handleCancel"
        >
          <img alt="example" style="width: 100%" :src="previewImage" />
        </a-modal>
      </a-form-item>

      <a-form-item
        style="width: 100%"
        ref="content"
        label="内容"
        name="content"
      >
        <a-textarea
          placeholder="请输入内容"
          v-model:value="formState.content"
          showCount
          :maxlength="120"
        />
      </a-form-item>
    </a-form>
  </div>
</template>
<script>
import {
  defineComponent,
  onMounted,
  reactive,
  ref,
  toRaw,
  toRef,
  toRefs,
  watch,
} from "vue";
import * as inventoryApi from "@/api/inventory.js";
import * as department from "@/api/department.js";
import { message } from "ant-design-vue";
import { getUserInfo } from "@/utils/auth";
import * as consumableApi from "@/api/consumable.js";
import { hospitalDepartList } from "@/api/hospitalDepart.js";
import * as utils from "@/utils/index.js";
import { PlusOutlined } from "@ant-design/icons-vue";
import { roleList } from "@/api/setting1.js";
import * as notificationApi from "@/api/notification.js";
const validateTitle = (rule, value, callback) => {
  if (!value) {
    callback(new Error("请输入公告标题"));
  } else if (
    value &&
    !/^[A-Za-z0-9]{1,100}$|^[\u4e00-\u9fa5A-Za-z0-9]{1,50}$/.test(value)
  ) {
    callback(new Error("公告标题不超过100个英文字符或50个汉字"));
  } else {
    callback();
  }
};
const typeList = [
  {
    name: "科室",
    value: "depart",
  },
  {
    name: "角色",
    value: "role",
  },
  {
    name: "接收人",
    value: "staff",
  },
];

const rules = {
  //form表单非空校验
  title: [
    {
      required: true,
      validator: validateTitle,
    },
  ],
  type: [
    {
      required: true,
      message: "请选择发布类型",
    },
  ],
  receiverRoleId: [
    {
      required: true,
      message: "请选择角色",
    },
  ],
  receiverDepartId: [
    {
      required: true,
      message: "请选择所属科室",
    },
  ],
  receiverIds: [
    {
      required: true,
      message: "请选择接收人",
    },
  ],
  content: [
    {
      required: true,
      message: "请输入内容",
    },
  ],
};
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);

    reader.onload = () => resolve(reader.result);

    reader.onerror = (error) => reject(error);
  });
}
export default defineComponent({
  props: {
    handleType: {
      type: String,
      default: "add",
    },
    handleRow: {
      type: Object,
      default: {},
    },
  },
  components: {
    PlusOutlined,
  },
  setup(props, { emit }) {
    const handleType = toRef(props, "handleType");
    const formRef = ref();
    const formState = reactive({
      content: "",
      id: "",
      type: "depart",
      receiverDepartId: null,
      receiverIds: [],
      receiverRoleId: null,
      title: "",
    });
    const userInfo = ref(getUserInfo() ? JSON.parse(getUserInfo()) : {});

    //获取人员列表数据
    const userList = ref([]);
    const handleGetUserList = () => {
      department.sysUserStaffList({ isPage: false }).then((res) => {
        if (res && res.success) {
          userList.value = res.data;
        }
      });
    };
    //获取角色列表
    const roleLists = ref([]);
    const handleGetRoleList = () => {
      roleList({ isPage: false }).then((res) => {
        if (res && res.success) {
          if (res.data) {
            roleLists.value = res.data.map((item) => {
              item.disabled = item.isFreeze == 1 ? true : false;
              return item;
            });
          }
        }
      });
    };
    // 获取科室数据
    const departmentList = ref([]);
    const getKSData = async () => {
      let res = await hospitalDepartList({
        isPage: false,
        name: "",
      });
      if (res && res.success) {
        let departmentListO = res.data.map((item) => {
          item.label = item.name;
          item.value = item.id;
          return item;
        });
        departmentList.value = utils.treeDataTranslate(departmentListO);
        console.log(123444444);
        console.log(departmentList.value);
      }
    };
    // 保存数据
    const handleSave = async () => {
      if (props.handleType == "look") {
        resetForm();
        emit("finish");
        return false;
      }
      let picUrl = [];
      for (let self of fileList.value) {
        const url = "";
        if (self.originFileObj) {
          url = await uploadData(self);
        } else {
          url = self.url;
        }

        picUrl.push(url);
      }
      formRef.value.validate().then(async () => {
        let params = {
          ...toRaw(formState),
        };
        notificationApi
          .noticeMessageSave({
            ...params,
            receiverDepartId:formState.type == 'depart' ? formState.hospitalDepartId:'',
            picUrl: picUrl.join(","),
          })
          .then((res) => {
            if (res && res.success) {
              message.success("操作成功");
              resetForm();
              emit("finish");
            } else {
            }
          });
      });
    };
    const resetForm = () => {
      formRef.value.resetFields();
    };

    //获取公告详情
    const handleGetNoteDetails = (_row) => {
      notificationApi.noticeMessageDetails(_row.id).then((res) => {
        if (res && res.success) {
          for (let self in res.data) {
            formState[self] = res.data[self];
          }
          if (res.data.picUrl) {
            formState.picUrl = res.data.picUrl
              ? res.data.picUrl.split(",").map((item) => {
                  return {
                    url: item,
                  };
                })
              : [];
            fileList.value = res.data.picUrl
              ? res.data.picUrl.split(",").map((item) => {
                  return {
                    url: item,
                  };
                })
              : [];
          } else {
            formState.picUrl = [];
            fileList.value = [];
          }
          console.log(formState);
        }
      });
    };

    // 上传
    const previewVisible = ref(false);
    const previewImage = ref("");
    const previewTitle = ref("");
    const fileList = ref([]);
    const handleCancel = () => {
      previewVisible.value = false;
      previewTitle.value = "";
    };
    const beforeUpload = (file) => {
      fileList.value = [...fileList.value, file];
      return false;
    };
    //图片上传
    const uploadData = async (file) => {
      let formData = new FormData();
      formData.append("file", file.originFileObj);
      let res = await notificationApi.uploadFile(formData);
      if (res && res.success) {
        return res.data;
      }
    };

    const handlePreview = async (file) => {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }

      previewImage.value = file.url || file.preview;
      previewVisible.value = true;
      previewTitle.value =
        file.name || file.url.substring(file.url.lastIndexOf("/") + 1);
    };

    onMounted(async () => {
      getKSData();
      handleGetUserList(),
       handleGetRoleList();
      if (props.handleType == "add") {
        formState.id = "";
        formState.type = "depart";
        return false;
      }
      handleGetNoteDetails(props.handleRow);
    });

    return {
      formRef,
      typeList,

      //  角色列表
      roleLists,
      // 接收人列表
      userList,
      // 科室列表
      departmentList, //
      handleType,
      userInfo,
      wrapperCol: {
        span: 0,
      },
      formState,
      rules,
      handleSave,
      resetForm,


      // 上传
      previewVisible,
      previewImage,
      fileList,
      handleCancel,
      handlePreview,
      previewTitle,

      uploadData,
      beforeUpload,
    };
  },
});
</script>
<style lang="scss">
.mask {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1000;
}
</style>